<!--
 * @Date: 2025-04-28 13:46:10
 * @LastEditors: Csir 2215995096@qq.com
 * @LastEditTime: 2025-06-17 17:03:39
 * @FilePath: \yujin-ui-admin\src\views\opticore\bomplcrel\index.vue
-->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item :label="t('opticore.bomplcrel.itemCode.label')" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          :placeholder="t('opticore.bomplcrel.itemCode.placeholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.itemName.label')" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          :placeholder="t('opticore.bomplcrel.itemName.placeholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.mateType.label')" prop="mateType">
        <el-select
          v-model="queryParams.mateType"
          :placeholder="t('opticore.bomplcrel.mateType.placeholder')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.table.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"
          ><Icon icon="ep:search" class="mr-5px" /> {{ t('common.button.search') }}</el-button
        >
        <el-button @click="resetQuery"
          ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.button.reset') }}</el-button
        >
        <el-button
          type="primary"
          plain
          @click="openForm('create', 0)"
          v-hasPermi="['opticore:bom-plc-rel:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('common.button.create') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['opticore:bom-plc-rel:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ t('common.button.export') }}
        </el-button>

        <el-button
          type="warning"
          plain
          @click="handleImport"
          :loading="importLoading"
          v-hasPermi="['opticore:bom-plc-rel:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> {{ t('action.import') }}
        </el-button>

        <!--        <el-button type="danger" plain @click="toggleExpandAll">-->
        <!--          <Icon icon="ep:sort" class="mr-5px" /> {{ t('common.expandCollapse') }}-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      border
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column :label="t('opticore.bomplcrel.table.index')" type="index" width="100" />
      <el-table-column
        :label="t('opticore.bomplcrel.table.itemCode')"
        align="center"
        prop="itemCode"
      />
      <el-table-column
        :label="t('opticore.bomplcrel.table.itemName')"
        align="center"
        prop="itemName"
      />
      <el-table-column
        :label="t('opticore.bomplcrel.table.mateType')"
        align="center"
        prop="mateType"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OPTICORE_MATE_TYPE" :value="scope.row.mateType" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('opticore.bomplcrel.table.unitName')"
        align="center"
        prop="unitName"
      />
      <el-table-column
        :label="t('opticore.bomplcrel.table.quantity')"
        align="center"
        prop="quantity"
      />
      <el-table-column
        :label="t('opticore.bomplcrel.table.drawingNo')"
        align="center"
        prop="drawingNo"
      />
      <el-table-column
        :label="t('opticore.bomplcrel.table.routeCode')"
        align="center"
        prop="routeName"
      />
      <el-table-column :label="t('opticore.bomlistplc.table.core')" align="center">
        <template #default="scope">
          <span v-if="scope.row.core === null || scope.row.core === undefined || scope.row.core === ''">/</span>
          <span v-else>{{ scope.row.core }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('opticore.bomplcrel.table.createTime')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.parent_id, scope.row.id)"
            v-hasPermi="['opticore:bom-plc-rel:update']"
          >
            {{ t('common.action.edit') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('create', scope.row.id)"
            v-hasPermi="['opticore:bom-plc-rel:create']"
          >
            {{ t('opticore.bomplcrel.table.addSubItem') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['opticore:bom-plc-rel:delete']"
          >
            {{ t('common.action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BomPlcRelForm ref="formRef" @success="getList" />

  <!-- 导入组件 -->
  <el-upload
    ref="uploadRef"
    class="hidden"
    :action="'http://localhost:48080/admin-api/opticore/bom-plc-rel/import'"
    :on-success="handleImportSuccess"
    :on-error="handleImportError"
    :before-upload="beforeUpload"
    :show-file-list="false"
    :headers="{ Authorization: 'Bearer ' + getAccessToken() }"
    accept=".xlsx,.xls"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      将文件拖到此处，或<em>点击上传</em>
      <div class="el-upload__tip"> 只能上传 xlsx/xls 文件，且不超过 2MB </div>
    </div>
  </el-upload>
  <BomImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import download from '@/utils/download'
import { BomPlcRelApi, BomPlcRelVO } from '@/api/opticore/bomplcrel'
import BomPlcRelForm from './BomPlcRelForm.vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { UploadFilled } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import BomImportForm from '@/views/opticore/bomplcrel/BomImportForm.vue'

/** 产品 列表 */
defineOptions({ name: 'BomPlcRel' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BomPlcRelVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  itemCode: undefined,
  itemName: undefined,
  mateType: undefined,
  createTime: [],
  pageNo: 1,
  pageSize: 10
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const importLoading = ref(false) // 导入的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BomPlcRelApi.getBomPlcRelPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, parent_id: number, id?: number) => {
  formRef.value.open(type, parent_id, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BomPlcRelApi.deleteBomPlcRel(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BomPlcRelApi.exportBomPlcRel(queryParams)
    download.excel(data, '产品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  refreshTable.value = true
}

/** 导入按钮操作 */
const importFormRef = ref()
const handleImport = () => {
  // uploadRef.value.$el.querySelector('input').click()
  importFormRef.value.open()
}

/** 导入前的校验 */
const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    message.error('只能上传 Excel 文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('文件大小不能超过 2MB!')
    return false
  }
  importLoading.value = true
  return true
}

/** 导入成功处理 */
const handleImportSuccess = (response: any) => {
  importLoading.value = false
  if (response.code === 0) {
    message.success('导入成功')
    getList() // 刷新列表
  } else {
    message.error(response.msg || '导入失败')
  }
}

/** 导入失败处理 */
const handleImportError = () => {
  importLoading.value = false
  message.error('导入失败，请重试')
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
